import type { StyleSpecification } from 'mapbox-gl';
import type Mapless from '..';
// import MapboxLanguage from '@mapbox/mapbox-gl-language';
import { MapboxLanguage } from './MapboxLanguage';

type Delimiter = '_' | ':';

class Lang {
  public map: mapboxgl.Map | null;
  public mapless: Mapless | undefined;

  private mblangTool: MapboxLanguage | undefined;

  constructor(mapless: Mapless, defaultLang = '', delimiter: Delimiter = '_') {
    this.mapless = mapless;
    this.map = this.mapless.map;

    const mb = new MapboxLanguage({
      defaultLanguage: defaultLang || 'zh-Hans',
    });
    this.map?.addControl(mb);
    this.mblangTool = mb;

    this.delimiter = delimiter;
  }

  private _delimiter: Delimiter = '_';
  set delimiter(delimiter: Delimiter) {
    this._delimiter = delimiter;
    const langField = delimiter === '_' ? /^name_/ : /^name:/;
    this.mblangTool?.setLanguageField(langField);
    this.mblangTool?.setGetLanguageField((language: string) => {
      return language === 'mul' ? 'name' : `name${delimiter}${language}`;
    });
  }
  get delimiter() {
    return this._delimiter;
  }

  getLangStyle(style: StyleSpecification, lang = '') {
    const ll = lang || this.mblangTool?.current;
    if (ll) {
      const ret = this.mblangTool?.setLanguage(style, ll);
      return ret;
    }
    return style;
  }

  switchLang(lang = '') {
    if (lang) {
      const style = this.map?.getStyle();
      if (style) {
        const ret = this.mblangTool?.setLanguage(style, lang);
        if (ret) {
          this.map?.setStyle(ret);
        }
      }
    }
  }

  /**
   * 切换Mapbox语言
   * @param lang
   * @see MapboxLanguage
   */
  switchMapboxLang(lang = 'zh-Hans') {
    // TODO 此处可以合并处理
    this.delimiter = '_';
    this.switchLang(lang);
  }

  /**
   * 切换DZMap语言
   * @param lang zh|nonlatin en|latin
   */
  switchDzmapLang(lang = 'zh') {
    this.delimiter = ':';
    this.switchLang(lang);
    // const layers = [
    //   'road_major_label',
    //   'water_name',
    //   'place_label_other',
    //   'place_suburb',
    //   'place_village',
    //   'place_town',
    //   'place_city_large',
    //   'place_state',
    //   'country_label',
    //   'road_major_label',
    // ];
    // layers.forEach((layer) => {
    //   if (this.map?.getLayer(layer)) {
    //     this.map?.setLayoutProperty(layer, 'text-field', [
    //       'get',
    //       `name:${lang}`,
    //     ]);
    //   }
    // });
  }

  destroy = () => {
    if (this.map && this.mblangTool) {
      this.map.removeControl(this.mblangTool);
      this.mblangTool = undefined;
    }
    this.map = null;
    this.mapless = undefined;
  };
}

export default Lang;
